package web_report

import (
	"encoding/json"
	"errors"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

const (
	AppId                = "有时面试"
	ScoreQueryType       = "自定义测评_分数"
	VocationalQueryType  = "自定义测评_职业能力解析"
	PersonalityQueryType = "自定义测评_大五人格解析"
)

type CustomWebReport struct {
	*DefaultWebReport
	askGlmReq *AskGlm
}

func (c *CustomWebReport) GetReq() *WrapAskGlm {
	// 适配启昌代码,封装一层参数message
	askGlm, _ := json.Marshal(c.askGlmReq)
	return &WrapAskGlm{Message: string(askGlm)}
}

func (c *CustomWebReport) SetCharacterData(*tables.RealQues) error {
	return nil
}

func (c *CustomWebReport) GetGlmResult() (string, error) {
	if c.askGlmReq == nil {
		c.Logger.Error("请求参数没有初始化")
		return "", errors.New("请初始化请求参数")
	}
	resp, err := c.HttpClient(c.GetReq(), variable.Config.Services.AskGlm, "POST")
	if err != nil {
		return "", err
	}
	var askGlmResp AskGlmResp
	if err := json.Unmarshal(resp, &askGlmResp); err != nil {
		return "", err
	}
	if askGlmResp.Data.Status != "success" {
		return "", errors.New("status字段不是success")
	}
	var getGlmResp GetGlmResultResp
	for i := 0; i < 60; i++ {
		result, err := c.HttpClient(c.askGlmReq, variable.Config.Services.GetGlmResult, "POST")
		if err != nil {
			return "", err
		}
		if err := json.Unmarshal(result, &getGlmResp); err != nil {
			return "", err
		}
		if getGlmResp.Data.ResText != "" {
			return getGlmResp.Data.ResText, nil
		}
		<-time.After(time.Second)
	}
	return "", errors.New("60s超时没有获取到结果")
}

func (c *CustomWebReport) GetTotalScore() float64 { // 获取分数
	userIdStr := strconv.Itoa(int(c.Session.UserID))
	var itvHistory string
	var flag = true // 是否调用大模型
	for _, q := range c.RealQues {
		if utf8.RuneCountInString(q.AnswerText) < 50 {
			itvHistory += "未提供有价值的信息"
		} else {
			flag = false
			itvHistory += q.AnswerText
		}
		itvHistory += "\n"
	}
	sessionId := strconv.Itoa(int(c.Session.ID))
	c.askGlmReq = &AskGlm{
		AppId:     AppId,
		QueryType: ScoreQueryType,
		UserId:    userIdStr + "_" + sessionId,
		PromptMap: &PromptMap{
			Job:        c.Session.CareerName,
			ItvHistory: itvHistory,
		},
	}
	// 无需调用大模型
	if flag {
		return 0.0
	}
	resp, err := c.GetGlmResult()
	if err != nil {
		c.Logger.Error(err.Error())
		return 0.0
	}
	sampleRegexp := regexp.MustCompile(`\d+\.*\d*`)
	match := sampleRegexp.FindAllString(resp, -1)
	if len(match) > 1 {
		c.Logger.Warn("分数返回结果中包含不止一个数")
	}
	if len(match) <= 0 {
		c.Logger.Error("分数返回结果中没有数值")
		return c.avgExpressiveScore*0.5 + c.avgThemeScore*0.5
	}
	score, _ := strconv.ParseFloat(match[0], 64)
	if score > 100 {
		return c.avgExpressiveScore*0.5 + c.avgThemeScore*0.5
	}
	return score
}

func (c *CustomWebReport) GetVocationalData() (interface{}, error) { // 职业能力解析
	c.askGlmReq.QueryType = VocationalQueryType
	c.askGlmReq.PromptMap.Ability = strings.Join(c.analyzeLabelsList, ",")
	return c.GetGlmResult()
}

func (c *CustomWebReport) GetPersonalityData() (interface{}, error) { // 大五人格解析
	c.askGlmReq.QueryType = PersonalityQueryType
	return c.GetGlmResult()
}

func (c *CustomWebReport) GetGuideData() (interface{}, error) {
	return nil, nil
}
